package com.cn.common.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: jia
 * @Descirption:
 * @Date: 2018/5/14 10:29
 * @Modified By:
 */


public class GsonHelperUtils {
    public static String toJson(Object obj){
        Gson gson = create();
        return gson.toJson(obj);
    }
    public static Gson create(){
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        return gson;
    }
    public static <T extends Object> T fromJson(String jsonData,Class<T> clazz){
        Gson gson = create();
        T t = gson.fromJson(jsonData, clazz);
        return t;
    }

    /**
     * 将json反序列化成数据
     *
     * @param jsonData
     * @param type
     * @return
     */
    public static <T extends Object> List<T> fromJson(String jsonData, Type type) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        List<T> list = gson.fromJson(jsonData, type);

        return list;
    }

    public static <V, M> Map<V, M> fromJsonToMap(String jsonData, Type type) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        HashMap<V, M> map = gson.fromJson(jsonData, type);

        return map;
    }
}
